package com.atguigu.crowd.handler;


import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpSession;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.atguigu.crowd.api.MySQLRemoteService;
import com.atguigu.crowd.api.RedisRemoteService;
import com.atguigu.crowd.config.ShortMessageProperties;
import com.atguigu.crowd.constant.CrowdConstant;
import com.atguigu.crowd.entity.po.MemberPO;
import com.atguigu.crowd.entity.vo.DetailProjectVO;
import com.atguigu.crowd.entity.vo.MemberLoginVO;
import com.atguigu.crowd.entity.vo.MemberVO;
import com.atguigu.crowd.entity.vo.OrderProjectVO;
import com.atguigu.crowd.entity.vo.PortalProjectVO;
import com.atguigu.crowd.util.CrowdUtil;
import com.atguigu.crowd.util.ResultEntity;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Objects;


@Controller
public class MemberHandler {
	
	@Autowired
	private ShortMessageProperties shortMessageProperties;

	@Autowired
	private RedisRemoteService redisRemoteService;
	
	@Autowired
	private MySQLRemoteService mySQLRemoteService;
	
	
	
	//更新我发起的项目
	@RequestMapping("/update/supprot/project")
	public String editProjectDetail(DetailProjectVO detailProjectVO,@RequestParam("projectId") Integer projectId,HttpSession session) {
		MemberLoginVO memberLoginVO = (MemberLoginVO)session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);
		ResultEntity<String> resultEntity = mySQLRemoteService.editProjectDetailRemote(detailProjectVO,projectId);
		//把会员id放入redis中，避免重定向到我的众筹页面丢失了登录的用户产生空指针异常
		String memberId = memberLoginVO.getId().toString();
		redisRemoteService.setRedisKeyValueRemote("memberId", memberId);
		return "redirect:/member/my/crowd";
	}
		
	//跳转我发起的项目编辑页面
	@RequestMapping("/edit/supprot/project/{projectId}")
	public String toEditUI(@PathVariable("projectId") Integer projectId,Model model) {

		ResultEntity<DetailProjectVO> resultEntity = mySQLRemoteService.showProjectDetailRemote(projectId);
		if (ResultEntity.SUCCESS.equals(resultEntity.getResult())) {
			DetailProjectVO detailProject = resultEntity.getData();
			model.addAttribute("detailProject", detailProject);
		}
		return "project-edit";
	}
		
	//刪除我发起的项目
	@RequestMapping("/del/supprot/project/{projectId}")
	public String delProjectDetail(@PathVariable("projectId") Integer projectId) {
		ResultEntity<String> resultEntity = mySQLRemoteService.delProjectDetailRemote(projectId);
		
		return "redirect:/member/my/crowd";
	}
	
	//查看发布项目详情信息
	@RequestMapping("/show/supprot/project/{projectId}")
	public String showProjectDetail(@PathVariable("projectId") Integer projectId,Model model) {
		ResultEntity<DetailProjectVO> resultEntity = mySQLRemoteService.showProjectDetailRemote(projectId);
		if (ResultEntity.SUCCESS.equals(resultEntity.getResult())) {
			DetailProjectVO detailProject = resultEntity.getData();
			model.addAttribute("detailProject", detailProject);
		}
		return "project-detail";
	}
	
	//刪除订单
	@RequestMapping("/del/order/detail/{orderId}")
	public String delOrderDetail(@PathVariable("orderId") Integer orderId) {
		ResultEntity<String> resultEntity = mySQLRemoteService.delOrderDetailRemote(orderId);
		
		return "redirect:/get/order/project";
	}
	
	//查看订单详情
	@RequestMapping("/show/order/detail/{orderId}")
	public String showOrderDetail(@PathVariable("orderId") Integer orderId,Model model) {
		ResultEntity<OrderProjectVO> resultEntity = mySQLRemoteService.showOrderDetailRemote(orderId);
		if (ResultEntity.SUCCESS.equals(resultEntity.getResult())) {
			OrderProjectVO orderDetail = resultEntity.getData();
			model.addAttribute("orderDetail", orderDetail);
		}
		return "order-detail";
	}
	//查询我支持的订单项目
	@RequestMapping("/get/order/project")
	public String getOrderProject(HttpSession session,Model model) {
		MemberLoginVO memberLoginVO = (MemberLoginVO)session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);
		Integer memberId = memberLoginVO.getId();
		ResultEntity<List<OrderProjectVO>> resultEntity = mySQLRemoteService.getOrderProjectRemote(memberId);
		if (ResultEntity.SUCCESS.equals(resultEntity.getResult())) {
			List<OrderProjectVO> orderProjectList = resultEntity.getData();
			model.addAttribute("orderProjectList", orderProjectList);
		}
		return "member-crowd";
	}
	
	//跳转我的众筹页面并查找我发起的的项目
	@RequestMapping("/member/my/crowd")
	public String toMyCrowd(HttpSession session,ModelMap map) {
		MemberLoginVO memberLoginVO = (MemberLoginVO)session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);
		Integer memberId;
		if (memberLoginVO==null) {//更新重定向到此处会丢失登录用户
			ResultEntity<String> resultEntity = redisRemoteService.getRedisStringValueByKeyRemote("memberId");
			String memberIdStr = resultEntity.getData();
			memberId = Integer.valueOf(memberIdStr);
		}else {
			
			 memberId = memberLoginVO.getId();
		}
		//查询已支持的项目
		ResultEntity<List<DetailProjectVO>> resultEntity = mySQLRemoteService.getLaunchProjectRemote(memberId);
		if (ResultEntity.SUCCESS.equals(resultEntity.getResult())) {
			List<DetailProjectVO> launchProjectList = resultEntity.getData();
			map.addAttribute("launchProjectList", launchProjectList);
		}
		return "member-crowd";
	}
	
	//退出登录
	@RequestMapping("/auth/member/logout")
	public String logout(HttpSession session) {
		session.invalidate();
		return "redirect:/";
	}
	
	//登录
	@RequestMapping("/auth/member/do/login")
	public String login(
			@RequestParam("loginacct") String loginacct,
			@RequestParam("userpswd") String userpswd,
			ModelMap modelMap,
			HttpSession session) {//org.springframework.session.web.http.SessionRepositoryFilter$SessionRepositoryRequestWrapper$HttpSessionWrapper@5f40d856
		//获取登录用户
		ResultEntity<MemberPO> resultEntity = mySQLRemoteService.getMemberPOByLoginAcctRemote(loginacct);
		if (ResultEntity.FAILED.equals(resultEntity.getResult())) {
			modelMap.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, resultEntity.getMessage());
			return "member-login";
		}
		MemberPO memberPO = resultEntity.getData();
		if (memberPO==null) {
			modelMap.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, CrowdConstant.MESSAGE_LOGIN_FAILED);
			return "member-login";
		}
		//判断密码
		String passwordDB = memberPO.getUserpswd();
		BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
		boolean result = passwordEncoder.matches(userpswd, passwordDB);
		if (!result) {
			modelMap.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, CrowdConstant.MESSAGE_LOGIN_FAILED);
			return "member-login";
		}
		
		//创建memberLoginVO存入session域中
		MemberLoginVO memberLoginVO = new MemberLoginVO(memberPO.getId(),memberPO.getUsername(),memberPO.getEmail());
		session.setAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER, memberLoginVO);
		return "redirect:http://localhost/auth/member/to/center/page";
	}
	
	
	//注册
	@RequestMapping("/auth/do/member/register")
	public String register(MemberVO memberVO,ModelMap map) {
		
		//获取手机号
		String phoneNum = memberVO.getPhoneNum();
		//获取key
		String key = CrowdConstant.REDIS_CODE_PREFIX+phoneNum;
		//从redis获取验证码
		ResultEntity<String> codeResultEntity = redisRemoteService.getRedisStringValueByKeyRemote(key);
		//检查操作是否有效
		if (ResultEntity.FAILED.equals(codeResultEntity.getResult())) {
			map.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, codeResultEntity.getMessage());
			return "member-reg";
		}
		//获取验证码
		String redisCode = codeResultEntity.getData();
		//判断验证码
		if (redisCode==null) {
			map.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, CrowdConstant.MESSAGE_CODE_NOT_EXIST);
			return "member-reg";
		}
		//获取表单验证码
		String formCode = memberVO.getCode();
		//判断验证码
		if (!Objects.equal(redisCode, formCode)) {
			map.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, CrowdConstant.MESSAGE_CODE_INVALED);
			return "member-reg";
		}
		//验证码一致，则删除redis中的验证码
		redisRemoteService.removeRedisKeyRemote(key);
		//密码加密
		BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
		String beforePassword = memberVO.getUserpswd();
		String aftrerPassword = passwordEncoder.encode(beforePassword);
		memberVO.setUserpswd(aftrerPassword);
		//保存注册信息
		MemberPO memberPO = new MemberPO();
		//拷贝
		BeanUtils.copyProperties(memberVO, memberPO);
		ResultEntity<String> saveMemberResultEntity = mySQLRemoteService.saveMember(memberPO);
		if (ResultEntity.FAILED.equals(saveMemberResultEntity.getResult())) {//用户账号已存在
			map.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, saveMemberResultEntity.getMessage());
			return "member-reg";
		}
		// 使用重定向避免刷新浏览器导致重新执行注册流程
		return "redirect:/auth/member/to/login/page";
	}
	
	//发送验证码
	@ResponseBody
	@RequestMapping("/auth/member/send/short/message.json")
	public ResultEntity<String> sendMessage(@RequestParam("phoneNum") String phoneNum){
		//发送验证码
		ResultEntity<String> sendMessageResultEntity = CrowdUtil.sendCodeByShortMessage2(
				shortMessageProperties.getHost(), 
				shortMessageProperties.getPath(), 
				shortMessageProperties.getMethod(), phoneNum, 
				shortMessageProperties.getAppCode(), 
				shortMessageProperties.getTemplateId());
		//判断发送是否成功
		if (ResultEntity.SUCCESS.equals(sendMessageResultEntity.getResult())) {
			//获取验证码
			String code = sendMessageResultEntity.getData();
			String key = CrowdConstant.REDIS_CODE_PREFIX+phoneNum;
			//将验证码存入redis中
			ResultEntity<String> savaCodeResultEntity = redisRemoteService.setRedisKeyValueRemoteWithTimeout(key, code, 15, TimeUnit.DAYS);
			//判断是否存入成功
			if (ResultEntity.SUCCESS.equals(savaCodeResultEntity.getResult())) {
				return ResultEntity.successWithoutData();
			}else {//存入失败
				return savaCodeResultEntity;
			}
		
		}else {//发送失败
			return sendMessageResultEntity;
		}
		
		
	}
}
